/**
 * @file 工单操作-派单
 * @author yangjiangming <449654337@qq.com>
 * @date 2018-12-10 20:13:16
 */
layui.define(['layer', 'form', 'element', 'table', 'zmnUtils', 'select2', '$http', '$api'], function (exports) {
    var $ = layui.$;
    var form = layui.form;
    var layer = layui.layer;
    var table = layui.table;

    var zmnUtils = layui.zmnUtils;
    var opCommonUtils = layui.list_modify_common;
    var $http = layui.$http;
    var $api = layui.$api;
    var select2 = layui.select2;

    var allMasterList = json.recommendMasterList;

    // 工程师远程查询 URL
    var MASTER_LIST_URL = '/staff/master/list.action';
    // 校验工程师派单
    var MASTER_CHECK_URL = '/work/modify/distribute/checkReason.action';

    var templeteFormatter = {
        masterInfoTempleteFunc: function (d) {
            return '<div><span class="master" id="' + d.masterId + '"></span></div>';
        },
        masterNameTempleteFunc: function (d) {
            var text = d.masterName + '—' + zmnUtils.maskPhone(d.masterPhone);
            var isReworkMaster = json.reworkMasterId === d.masterId;
            var showVoice = d.nonDistributeFlag === undefined;

            return (`
               <div>
                   <div>
                        <span>${ text }</span>
                        ${ d.distributeRuleTitle ? `<span class="layui-badge layui-bg-green">${d.distributeRuleTitle}</span>` : '' }
                        ${ isReworkMaster ? '<span class="layui-badge">源工程师</span>' : '' }
                        ${ canNetCall && showVoice ? `<a class="zmn-btn-text btn-netcall" data-id="${ d.masterId }"><i class="zmn-icon zmn-icon-voice"></i></a>` : '' }
                    </div>
                </div>
            `);
        }
    }

    var createTableCols = (function () {
        var cols = [[
                { type: 'radio', hide: true },
                { field: 'masterName', title: '工程师（双击可选中工程师）', sort: true, templet: templeteFormatter.masterNameTempleteFunc },
                {field: 'starLevel', title: '星级', sort: true, align: 'center'},
                { field: 'distance', title: '距离', sort: true, templet: function (data) { return data.distance ? data.distance+'KM' : ''; }},
                { field: 'monthReworkCount', title: '当月已派他人返修单', sort: true, align: 'center' },
                { field: 'handReworkCount', title: '手头返修单（不含待件&拉修）', sort: true, align: 'center' },
                { field: 'masterId', title: '占位列', hide: true, templet: templeteFormatter.masterInfoTempleteFunc }
            ]];
        return function () {
            return cols;
        }
    })(json);

    /**
     * 打电话
     * @param masterId 工程师 id
     */
    function makeRadioCall(masterId) {
        var LOCAL_ITEM_NAME = 'distribute_voice_tips';
        var noTips = window.localStorage.getItem(LOCAL_ITEM_NAME);

        if (noTips === 'off') {
            zmnUtils.makeCall({ masterId: masterId });
            return;
        }

        //自定页
        layer.open({
            type: 1,
            title: '提示',
            skin: 'modal-distribute', //样式类名
            closeBtn: 1,
            anim: 2,
            area: '425px',
            shadeClose: true,
            content: $('#modal-voice-wrapper').html(),
            success: function ($layer, index) {
                $layer.find('.layui-btn').attr('lay-filter', 'form-modal');
                form.render();

                form.on('submit(form-modal)', function (data) {
                    if (data.field.noTips === 'on') {
                        window.localStorage.setItem(LOCAL_ITEM_NAME, 'off');
                    }
                    layer.close(index);
                    zmnUtils.makeCall({ masterId: masterId });

                    return false;
                });
            }
        });
    }

    /**
     * 呼叫中心打电话
     * @param telephone
     */
    function makeCallCenterCall(telephone) {
        top.postMessage({
            type: 2,
            phone: telephone
        }, '*');
    }

    /**
     * 检查当前的派单状态
     */
    function checkDistributeState () {
        var def = $.Deferred();
        var hasMaster = !!json.masterId;

        if (hasMaster) {
            //自定页
            layer.open({
                type: 1,
                title: '提示',closeBtn: 1,
                skin: 'modal-distribute',
                closeBtn: 1,
                anim: 2,
                area: '425px',
                shadeClose: true,
                content: $('#modal-distribute-wrapper').html(),
                success: function ($layer, index) {
                    $layer.on('click', '#btn-confirm', function () {
                        def.resolve();
                        layer.close(index);
                    });

                    $layer.on('click', '#btn-cancel', function () {
                        def.reject();
                        layer.close(index);
                    });
                }
            });
        } else {
            def.resolve();
        }

        return def.promise();
    }

    /**
     * 检查工程师是否可派单
     */
    function checkMasterDistributable (params) {
        var def = $.Deferred();
        var masterId = +params.masterId;
        var master;

        // 如果是推荐派单
        if (json.recommendStatus && !json.simpleStatus) {
            master = json.recommendMasterList.find(function (item) {
                return item.masterId === masterId;
            });
        } else {
            // 如果是简单派单先走简单派单
            master = json.masterList.find(function (item) {
                return item.masterId === masterId;
            });
        }

        if (master) {
            def.resolve(masterId, '可派单');
        } else {
            $http.get(MASTER_CHECK_URL, params).then(function (data) {
                if (data.status === 2) {
                    def.resolve(masterId, data.reason);
                } else {
                    def.reject(data.reason);
                }
            }, function (msg) {
                layer.msg(msg);
                def.reject('校验失败');
            });
        }

        return def.promise();
    }

    /**
     * 使用 Select2 初始化工程师下拉框
     */
    function initMasterSelecteBySelect2 () {
        select2.initRemote({
            el: '#select-master',
            url: MASTER_LIST_URL,
            placeholder: '输入工程师姓名校验是否可派单',
            getParams: function (params) {
                return {
                    text: params.term,
                    companyId: $('#companyId').val(),
					manageCompanyId: $('#manageCompanyId').val(),
                    cityId: $('#cityId').val(),
                    plat : json.plat
                };
            },
            processor: function (data) {
                return data.map((item) => {
                    item.id = item.value;
                    return item;
                });
            },
            formatRepo: formatRepoForMaster
        });
    }

    /**
     * 格式化工程师列表列表项
     * @param {object} repo
     * @returns {string}
     */
    function formatRepoForMaster (repo) {
        if (repo.loading) {
            return '查询中...'
        }
        var name = repo.text + (repo.disabled ? '（离职）' : '');
        var markup = '<div><div><i class="zmn-icon zmn-icon-worker"></i><span>' + name + '</span></div><div><i class="zmn-icon zmn-icon-phone"></i><span>' + repo.ext1 + '</span></div></div>';

        return markup;
    }

    function renderDetailMasterList (data) {
        table.render({
            elem: '#detailMasterTable',
            height: 400,
            limit: 1000,
            data: data,
            skin: 'line',
            cols: createTableCols(),
            done: function (res, curr, count) {
                var re = res.data;
                if (re.length > 0) {
                    for (var i in res.data) {
                        var item = res.data[i];
                        if (item.nonDistributeFlag != undefined) {
                            $('tr[data-index=' + i + ']').prop('disabled', true);
                            $("tr[data-index='" + i + "']").attr({"style": "background:#F2F2F2;color:#999999"});  //将当前行变成绿色
                        }
                    }
                }
            }
        });
    }

    function initTableViewOfMasterList (data) {
        renderDetailMasterList(data);
    }

    function updateMasterSelect(masterId, masterInfo) {
        form.val('zmn-work-form', {masterId: masterId});
        $('#masterId').val(masterInfo);
    }

    function updateMasterListTable (masterId) {
        var tableWrapperList = $('#mapView, #tableView');

        tableWrapperList.find('input[type="radio"]').prop('checked', false);
        tableWrapperList.find('.layui-table-main tr.current').removeClass('current');
        tableWrapperList.find('span.master[id="' + masterId + '"]')
            .closest('tr')
            .addClass('current')
            .find('input[type="radio"]')
            .prop('checked', true);
        form.render('radio');

        allMasterList.forEach((master) => {
            if (master.masterId === +masterId ) {
                master['LAY_CHECKED'] = true;
            } else {
                master['LAY_CHECKED'] = false;
            }
        });
    }

    /**
     * 更新语音按钮状态
     * @param {boolean} disabled 是否禁用
     */
    function updateVoiceStatus (disabled) {
        var $voiceBtn = $('.zmn-btn-voice');
        $voiceBtn.prop('disabled', disabled);

        if (disabled) {
            $voiceBtn.addClass('layui-btn-disabled');
        } else {
            $voiceBtn.removeClass('layui-btn-disabled');
        }
    }


    /**
     * 初始化页面
     */
    function initPage() {
        initTableViewOfMasterList(json.masterList);
    }

    /**
     * 初始化页面事件
     */
    function initEvent () {
        // 改派缘由
        form.on('radio(distributeReason)', function(obj) {
            if (obj.elem.checked) {
                $('#liableTypeName').text($(this).data('liable-type-name'));
            } else {
                $('#liableTypeName').text('');
            }
        });

        form.on('submit(distribute)', function (data) {
            if (data.field.masterId === '') {
                layer.msg('请选择工程师');
                return false;
            }
            if (!!json.masterId) {
                if (!data.field.distributeReasonId) {
                    layer.msg('请选择改派缘由');
                    return false;
                }
                // 获取改派缘由
                let $distributeReason = $('input[name="distributeReasonId"]:checked');
                data.field.distributeReason = $distributeReason.attr('title');
                data.field.liableType = $distributeReason.data('liable-type');
            }

            checkDistributeState().then(function () {
                $http.lockSave(data.form.action, data.field, data.elem).then(function () {
                    layer.msg('派单保存成功', {icon: 1, time: 1000}, function () {
                        opCommonUtils.goOperateHome();
                    });
                }, function (msg) {
                    layer.msg(msg);
                });
            });

            return false;
        });

        // 监听网络电话按钮
        form.on('submit(call)', function (data) {
            var masterId = data.field.masterId;
            if(masterId === ''){
                layer.msg('请选择工程师');
                return false;
            }
            makeRadioCall(masterId);
            return false;
        });

        // 初始化呼叫电话组件
        (function initCallForCC () {
            if (!top.isCallCenter) {
                return;
            }

            $('#btn-cc-call').removeClass('layui-hide');

            // 监听呼叫电话按钮
            form.on('submit(cc-call)', function (data) {
                var masterId = data.field.masterId;
                if(masterId === ''){
                    layer.msg('请选择工程师');
                    return false;
                }

                var $option = $('#masterSelect option[value="' + masterId + '"]');
                var telephone = $option.data('telephone');
                if (telephone) {
                    makeCallCenterCall($option.data('telephone'));
                } else {
                    $api.masterGetDetail({ masterId: masterId }).then((info) => {
                        var telephone = info.mobile;
                        $option.data('telephone', telephone);
                        makeCallCenterCall(telephone);
                    }, (msg) => {
                        zmnUtils.layui.toastError('工程师电话获取失败');
                    });
                }

                return false;
            });
        }());

        form.on('select(masterSelect)', function (data) {
            var masterId = data.value;

            updateMasterListTable(masterId);
            updateVoiceStatus(!masterId);
        });

        form.on('submit(check-master)', function (data) {
            var masterId = $('#select-master').val();
            var params = data.field;
            if (!masterId) {
                zmnUtils.layui.toastError('请先选择要校验的工程师');
                return false;
            }
            params.masterId = masterId;

            var setCheckResultMessage = function (result, msg) {
                $('#master-check-msg').removeAttr('class')
                .addClass(result)
                .text(msg);
            };

            checkMasterDistributable(params).then(function (masterId, msg) {
                setCheckResultMessage('success', msg);
            }, function (msg) {
                setCheckResultMessage('fail', msg);
            });

            return false;
        });


        table.on('radio(tableOfMatserList)', function (obj) {
            var masterId = obj.data.masterId;
            var masterInfo = obj.data.masterName + '—' + zmnUtils.maskPhone(obj.data.masterPhone);
            updateMasterSelect(masterId, masterInfo);
            updateVoiceStatus(!masterId);
        });

        table.on('rowDouble(tableOfMatserList)', function(obj){
            var $this = $(obj.tr);
            $this.addClass('current')
                .siblings('tr')
                .removeClass('current');

            if (obj.data !== null && obj.data.nonDistributeFlag === undefined) {
                $this.find('.layui-form-radio .layui-icon').trigger('click');
            }
        });

        // 初始化电话组件
        $('body').on('click', '.btn-netcall', function () {
            var masterId = $(this).data('id');
            makeRadioCall(masterId);
        });
    }



    // 程序入口
    function init () {
      // 初始化页面
      initPage();

      initMasterSelecteBySelect2();
      // 初始化事件
      initEvent();

    }


    // 初始化
    init();

    exports('oms_work_modify_biztypec_rework_distribute');
});
